from app.user.model import User
from app.user.model import Role, UserToRole
from app.company.model import Company
# from app.user.abs_model import User
from exts import db
from app.company import service as company_service
from common.mixins import DictMixin
from flask import g
import re
from common import errors
import random
from middleware.redis import set_phone_captcha
from middleware.sms import send_captcha_by_sms
import uuid

DEFAULT_COMPANY_NAME = "默认公司名称"


# ---------- route ----------
def register(phone, password, company_name=None, username=None, email=None):
    # 需要先commit
    new_company = Company.create(name=company_name if company_name else DEFAULT_COMPANY_NAME, commit=True)

    default_username = "默认用户名{}".format(uuid.uuid4())
    new_user = User.register(
        username=username if username else default_username, phone=phone, password=password, email=email,
        company_id=new_company.id,
        # commit=True
    )
    g.user_id = new_user.id
    g.company_id = new_company.id

    # 添加角色关联
    role = Role.query.filter_by(name="超级管理员", company_id=None).first()
    UserToRole.create(user_id=new_user.id, role_id=role.id)

    # 增加默认值
    company_service.init_company_info()

    db.session.commit()

    # 获取token
    token = new_user.login_get_token(password=password)
    return token


def send_captcha(phone):
    # 手机号码校验 (前端正则校验过，后端再校验一次)
    if not check_phone_number(phone):
        raise errors.BadRequestError("手机号格式不正确")
    # 生成验证码
    captcha = ''.join(random.sample('1234567890', 6))
    # redis 保存 手机号 验证码
    set_phone_captcha(phone, captcha)
    # 发送短信
    send_captcha_by_sms(phone, captcha)


def update_user_to_role(user_id, role_ids):
    # todo 非超级管理员无法成为超级管理员
    # 全部删除
    old_user_to_roles = UserToRole.query.filter_by(id=user_id).all()
    for old_user_to_role in old_user_to_roles:
        db.session.delete(old_user_to_role)
    # 重新创建
    for role_id in role_ids:
        UserToRole.create(user_id=user_id, role_id=role_id)
    db.session.commit()


# ---------- func ----------
def check_phone_number(phone):
    ret = re.match(r"^1[35678]\d{9}$", phone)
    if ret:
        return True
    return False


if __name__ == '__main__':
    from app import create_app

    app = create_app("default")
    with app.app_context():
        from common.constant import secret

        User.create_super_admin(username=secret.SUPER_ADMIN_USERNAME, password=secret.SUPER_ADMIN_PASSWORD)
